﻿using ConfExpert.Forms.Base;
using DevTeam;
using System;
using System.Data;
using System.Windows.Forms;

namespace ConfExpert.Forms.Araclar
{
    public partial class ConsolidateSheets : XForm
    {
        public ConsolidateSheets()
        {
            InitializeComponent();
        }

        private void ConsolidateSheets_Load(object sender, EventArgs e)
        {
            ds.Clear();
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
                if (openFileDialog1.OpenFile() != null)
                {
                    DataTable dt = ReadExcel(openFileDialog1.FileName);
                    if (dt == null)
                        return;

                    gridView1.Init(dt);
                }
        }


        public DataTable ReadExcel(string filename)
        {
            SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook(filename);
            System.Data.DataSet dataSet = workbook.GetDataSet(SpreadsheetGear.Data.GetDataFlags.NoColumnHeaders);

            bool firstrow = false;
            foreach (DataTable d in dataSet.Tables)
            {
                d.Columns.Add("SheetName", typeof(string));

                foreach (DataRow r in d.Rows)
                    r["SheetName"] = d.TableName;

                if (!firstrow)
                {
                    d.Rows.RemoveAt(0);
                    firstrow = true;
                }
                else
                    dataSet.Tables[0].Merge(d);
            }

            return dataSet.Tables[0];

        }

    }
}
